var socketio = {}
var cors = require('cors')
const { UsersModel, privateHistory, groupHistory } = require('./model/model')
let socketId = []//用账号对应客户端
//内容
/**
 * {
 *    account:xxx,
 *    socket_id:xxx
 * }
 */
socketio.getsocketio = function (server) {
    //socket.io初始化 及 配置跨域
    const io = require('socket.io')(server, { cors: true })
    //监听用户连接事件
    io.on('connection', async (socket) => {
        console.log('链接成功' + socket.id);
        //获取所有用户
        let docs = await UsersModel.find().exec()
        //发送用户列表
        socket.emit('allUsers', docs)


        //记录刷新后客户端连接ID
        socket.on('saveSocketId', data => {
            socketId[data] = socket.id
            socket.account = data
        })

        //message所有私信的最新消息
        socket.on('reqLatestPrivateHistory', async (data) => {
            let docs = await privateHistory.find({ selfaccount: data })
            let alls = await UsersModel.find()
            var latest = []
            for (var i = 0; i < docs.length; i++) {
                let img = alls.find(item => item.account == docs[i].otheraccount).avatar
                console.log(img);
                latest[i] = { othername: docs[i].othername, otheraccount: docs[i].otheraccount, latestmsg: docs[i].chathistory[docs[i].chathistory.length - 1], otheravatar: img }
            }
            //发送最新消息给前端
            socket.emit('getLatestPrivateHistory', latest)
        })

        //保存聊天记录并发送给对方
        socket.on('sendMsg', async (data) => {
            console.log('sendmsg');
            //为自己添加聊天记录
            let docs = await privateHistory.updateOne({ $and: [{ selfaccount: data.selfaccount }, { otheraccount: data.otheraccount }] }, { $set: { chathistory: data.chathistory } }, { multi: true })
            var otherhistory = data.chathistory
            for (let i = 0; i < otherhistory.length; i++) {
                otherhistory[i].self = !data.chathistory[i].self
            }
            //为对方添加聊天记录
            let docs2 = await privateHistory.updateOne({ $and: [{ selfaccount: data.otheraccount }, { otheraccount: data.selfaccount }] }, { $set: { chathistory: otherhistory } }, { multi: true })
            if (data.otheraccount in socketId) {
                io.to(socketId[data.otheraccount]).emit('sendToOther', otherhistory)
                let res = await privateHistory.find({ selfaccount: data.otheraccount })
                let latest = []
                for (let i = 0; i < res.length; i++) {
                    latest[i] = { othername: res[i].othername, otheraccount: res[i].otheraccount, latestmsg: res[i].chathistory[docs[i].chathistory.length - 1] }
                }
                //使用io.to(socketId) 为某个用户单独发射事件
                io.to(socketId[data.otheraccount]).emit('getLatestPrivateHistory', latest)
            }
        })


        //获取私聊的历史信息
        socket.on('getPrivateHistory', async (data) => {
            let docs = await privateHistory.find({
                selfaccount: data.selfaccount, otheraccount: data.otheraccount
            })
            if (docs.length > 0) {
                //发射所有聊天记录给前端
                socket.emit('sendPrivateHistory', { othername: docs[0].othername, chathistory: docs[0].chathistory })
            } else {
                //没有则创建聊天记录，并将记录设置为[]
                await privateHistory.create({
                    selfname: data.selfname, selfaccount: data.selfaccount, othername: data.othername, otheraccount: data.otheraccount, chathistory: []
                })
                await privateHistory.create({
                    selfname: data.othername, selfaccount: data.otheraccount, othername: data.selfname, otheraccount: data.selfaccount, chathistory: []
                })
                socket.emit('sendPrivateHistory', { chathistory: [] })
            }
        })
        //断开连接
        socket.on('disconnect', function () {
            if (socket.account in socketId) {
                socketId.splice(socket.account, 1);
                // delete(socketId[socket.account])
                // users.splice(users.indexOf(socket.account), 1)
                console.log("断开连接" + socket.id)
            }
        })

        //登录(登录接口暂时未用到)
        socket.on('login', async (data) => {
            console.log(data);
            let docs = await UsersModel.find({ account: data.account }).exec()
            console.log(docs);
            if (docs.length > 0 && data.password == docs[0].password) {
                socket.emit('loginRes', { state: true, res: docs[0].name, avatar: docs[0].avatar, account: docs[0].account })
                socketId[docs[0].account] = socket.id
                socket.account = docs[0].account
            } else {
                socket.emit('loginRes', { state: false, res: 'password error' })
            }
        })
    })
}
module.exports = socketio;